package cn.whitecao.agent.core.trace;

import cn.whitecao.agent.core.model.TraceModel;

/**
 * 为链路做准备 每次servlet(rpc等如dubbo这些涉及服务提供的组件)进来的时候都生成一个 traceId(先判断是否有带过来,有就用带过来的)出去的时候清理掉
 * 因为在线程池中使用threadLocal需要清理这个操作 不然会存在泄漏问题
 * 在后面切rpc,如dubbo之类的也需要进行清理操作
 * @author : BashfulHuang
 **/

public class TraceContext {
    private static final ThreadLocal<TraceModel> TRACE_CONTEXT_THREAD_LOCAL =new InheritableThreadLocal<>();


    public static TraceModel get(){
        TraceModel traceModel = TRACE_CONTEXT_THREAD_LOCAL.get();
        if (traceModel==null) {
            traceModel=create();
        }
        return traceModel;
    }

    public static TraceModel create(){
        TraceModel traceModel = new TraceModel();
        TRACE_CONTEXT_THREAD_LOCAL.set(traceModel);
        return traceModel;
    }
    public static TraceModel create(String traceId,String parentSpanId){
        TraceModel model = create();
        model.setParentSpanId(parentSpanId);
        model.setTraceId(traceId);
        return model;
    }
    public static void remove(){
        TRACE_CONTEXT_THREAD_LOCAL.remove();
    }


}
